package com.sanjiahantang.ythshopping.activity.me;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sanjiahantang.ythshopping.R;
import com.sanjiahantang.ythshopping.activity.GoodsFilterActivity;
import com.sanjiahantang.ythshopping.activity.GoodsInfoActivity;
import com.sanjiahantang.ythshopping.activity.MainActivity;
import com.sanjiahantang.ythshopping.alipay.PayResult;
import com.sanjiahantang.ythshopping.config.ConfigValue;
import com.sanjiahantang.ythshopping.model.AliPatModel;
import com.sanjiahantang.ythshopping.model.WXpayModel;
import com.sanjiahantang.ythshopping.model.WebPayModel;
import com.sanjiahantang.ythshopping.presenter.PayActivePresenter;
import com.sanjiahantang.ythshopping.presenter.WebPayPresenter;
import com.sanjiahantang.ythshopping.qrzxing.CaptureActivity;
import com.sanjiahantang.ythshopping.views.PayActiveView;
import com.sanjiahantang.ythshopping.views.WebPayView;
import com.sanjiahantang.shopping.uilibrary.uiutils.Utils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Map;

public class   WebActivity extends Activity implements WebPayView,PayActiveView{

    WebView wv_ad;
    TextView tv_tetile;
    ImageView iv_back;
    private View bar,errorView;
    int paytype=1;
    WebPayPresenter webPayPresenter;
    String aliinfo="";
    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;
    private boolean loadError = false;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Intent intent=new Intent(WebActivity.this, MainActivity.class);
                        startActivity(intent);
                        com.sanjiahantang.ythshopping.utils.Utils.showToast(WebActivity.this, "支付成功");
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            com.sanjiahantang.ythshopping.utils.Utils.showToast(WebActivity.this,"支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            com.sanjiahantang.ythshopping.utils.Utils.showToast(WebActivity.this, "支付失败");
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    if (!(boolean) msg.obj)
                        com.sanjiahantang.ythshopping.utils.Utils.showToast(WebActivity.this, "检查结果为：" + msg.obj);
                    else {

                    }
                    break;
                }
                default:
                    break;
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        InitView();
    }

    public void InitView ()
    {
        tv_tetile= (TextView) findViewById(R.id.title);
        tv_tetile.setVisibility(View.VISIBLE);
        iv_back= (ImageView) findViewById(R.id.back);
        wv_ad= (WebView) findViewById(R.id.wv_home_ad);
        bar=findViewById(R.id.web_bar);
        errorView = findViewById(R.id.errorView);
        if (getIntent().getStringExtra("type").equals("1"))
        {
            bar.setVisibility(View.VISIBLE);
            tv_tetile.setText(getIntent().getStringExtra("title"));
        }else {
            bar.setVisibility(View.GONE);
        }
        WebSettings webSettings = wv_ad.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        wv_ad.loadUrl(getIntent().getStringExtra("url"));

        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //设置Web视图
        wv_ad.setWebViewClient(new webViewClient ());
        wv_ad.setWebChromeClient(new webChromeClient());
        webPayPresenter=new WebPayPresenter(this,this);


        wv_ad.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && wv_ad.canGoBack()) {  //表示按返回键


                        wv_ad.goBack();   //后退

                        //webview.goForward();//前进
                        return true;    //已处理
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void rePayMsg(WebPayModel model) {
        PayActivePresenter payActivePresenter=new PayActivePresenter(this,this,model.getData(),model.getData().getSid()+"");
        if (paytype==1)
        {
            payActivePresenter.LoadsqAliPay();
        }else
        {
            payActivePresenter.LoadSQWXPay();
        }

    }

    @Override
    public void getWXinfo(WXpayModel wxpay) {
        if (wxpay.getCode().equals("1")) {
            final IWXAPI api = WXAPIFactory.createWXAPI(this, null);
            // 将该app注册到微信
            api.registerApp(ConfigValue.WXAPP_ID);

            PayReq req = new PayReq();

            req.appId = wxpay.getData().getPayinfo().getAppId();

            req.partnerId = wxpay.getData().getPayinfo().getPartnerId();
            req.prepayId = wxpay.getData().getPayinfo().getPrepayId();
            req.packageValue = "Sign=WXPay";
            req.nonceStr = wxpay.getData().getPayinfo().getNonceStr();
            req.timeStamp = wxpay.getData().getPayinfo().getTimeStamp();
            req.sign = wxpay.getData().getPayinfo().getSign();
            api.sendReq(req);


            finish();
        }else {
            Toast.makeText(this,wxpay.getMsg(),Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void getALiinfo(AliPatModel ali) {
        aliinfo=ali.getData().getPayinfo();
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    Runnable payRunnable = new Runnable() {

        @Override
        public void run() {
            PayTask alipay = new PayTask(WebActivity.this);
            String result = alipay.pay(aliinfo);

            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    private void onLoadAndroidPage(int index){
        setResult(index,getIntent().putExtra("index",index));
        WebActivity.this.finish();
    }
    //Web视图
    private class webViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            loadError = false;
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            loadError = true;
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            loadError = true;
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                return true;
            }



            if (Build.VERSION.SDK_INT >= 23) {
                int checkPermission = ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
                if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
                    ActivityCompat.requestPermissions(WebActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                    Log.d("TTTT", "弹出提示");
                }
            }

            String lowerUrl = url.toLowerCase();
            Log.e("JsWebActivity",url);

            //分类
            if (lowerUrl.contains("/category.php")){
                Intent mIntent = new Intent(WebActivity.this,GoodsFilterActivity.class);
                Map map = Utils.URLRequest(url);
                mIntent.putExtra("id",map.get("id").toString());
                startActivity(mIntent);
                return true;
            }

            //分类
            if (lowerUrl.contains("/catalog.php")){
                onLoadAndroidPage(1);
//                startActivity(new Intent(WebActivity.this, MainActivity.class).putExtra("index",1));
                return true;
            }
            //首页
            if (lowerUrl.contains("/index.php") || lowerUrl.endsWith("mobile/") || lowerUrl.contains("mobile/?")){
                onLoadAndroidPage(0);
                return true;
            }

            //购物车
            if (lowerUrl.contains("/flow.php")){
                onLoadAndroidPage(3);
                return true;
            }

            //用户
            if (lowerUrl.contains("/user.php")){
                Map map = Utils.URLRequest(url);
                if(lowerUrl.contains("act=relogin")){
                    startActivity(new Intent(WebActivity.this, LoginActivity.class));
                    WebActivity.this.finish();
                }else if(map == null || !map.containsKey("act") || map.get("act").toString().contains("login") || map.get("act").toString().contains("default")){
                    onLoadAndroidPage(4);
                    return true;
                }


            }

            //商品
            if (lowerUrl.contains("/goods.php")){
                Map map = Utils.URLRequest(url);
                Intent mIntent = new Intent(WebActivity.this, GoodsInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("goodsId",map.get("id").toString());
                mIntent.putExtras(bundle);
                startActivity(mIntent);
                return true;
            }

            // 联盟商家
            if (lowerUrl.contains("/lmshop.php")){
                Map map = Utils.URLRequest(url);
                if (map == null || !map.containsKey("act") || map.get("act").toString().contains("shop_index")){
                    onLoadAndroidPage(2);
                    return true;
                }
            }

            if (lowerUrl.contains("/alipayapi.php"))
            {
                paytype=1;
                Map map = Utils.URLRequest(url);
                if (map!=null)
                {
                    webPayPresenter.LoadPayMsg(map.get("out_trade_no").toString());
                }
                return true;

            }
            if (lowerUrl.contains("/weixinpay.php"))
            {
                paytype=2;
                Map map = Utils.URLRequest(url);
                if (map!=null)
                {
                    webPayPresenter.LoadPayMsg(map.get("out_trade_no").toString());
                }
                return true;
            }
//            if (url.indexOf("from_app")<=0)
//            {
//
//                if(url.indexOf("?")>0)
//                {
//                    url=url+"&from_app=2&key="+ConfigValue.DATA_KEY + "&rid=" + ConfigValue.rid;
//                }else {
//                    url=url+"?from_app=2&key="+ConfigValue.DATA_KEY + "&rid=" + ConfigValue.rid;
//                }
//            }
            view.loadUrl(url);
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            if(loadError){
                view.setVisibility(View.GONE);
                errorView.setVisibility(View.VISIBLE);
            }else {
                view.setVisibility(View.VISIBLE);
                errorView.setVisibility(View.GONE);
            }
            CookieManager cookieManager = CookieManager.getInstance();
            String CookieStr = cookieManager.getCookie(url);
            Log.e("sunzn", "Cookies = " + CookieStr);
            super.onPageFinished(view, url);
        }
    }


    private class webChromeClient extends WebChromeClient {


        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            return super.onJsBeforeUnload(view, url, message, result);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            if (message != null && message.contains("微信")){
                loadScanView();
                return true;
            }
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
            Log.i("test", "onGeolocationPermissionsHidePrompt");
        }

        //网页权限弹窗
        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin,
                                                       final GeolocationPermissions.Callback callback) {
            AlertDialog.Builder builder = new AlertDialog.Builder(WebActivity.this);
            builder.setMessage("允许访问位置信息?");
            DialogInterface.OnClickListener dialogButtonOnClickListener = new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int clickedButton) {
                    if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
                        callback.invoke(origin, true, true);
                    } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
                        callback.invoke(origin, false, false);
                    }
                }
            };
            builder.setPositiveButton("允许", dialogButtonOnClickListener);
            builder.setNegativeButton("拒绝", dialogButtonOnClickListener);
            builder.show();
            super.onGeolocationPermissionsShowPrompt(origin, callback);
            Log.i("test", "onGeolocationPermissionsShowPrompt");
        }

    }

    private void loadScanView(){
        if (com.sanjiahantang.ythshopping.utils.Utils.NO_NETWORK_STATE == com.sanjiahantang.ythshopping.utils.Utils.isNetworkAvailable(WebActivity.this)) {
            return;
        }
        if (ContextCompat.checkSelfPermission(WebActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
            }

        } else {
            Intent itCapture = new Intent(WebActivity.this, CaptureActivity.class);
            itCapture.putExtra("type","home");
            startActivity(itCapture);

        }

    }
}
